﻿using Activity.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;

namespace Activity.Model
{
    public class BasePage : Page, IRequiresSessionState
    {
        internal static void SetHeader(HttpResponse Response)
        {
            Response.ClearHeaders();
            Response.AddHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Access-Control-Request-Method,X_FILENAME");
            Response.AddHeader("Access-Control-Allow-Methods", "GET,PUT,POST,HEAD,DELETE,OPTIONS");
            Response.AddHeader("Access-Control-Max-Age", "360000");
            Response.AddHeader("Access-Control-Allow-Credentials", "true");
            //Response.AddHeader("Access-Control-Allow-Origin", "*");
        }

        #region 打印Json的相关处理
        /// <summary>
        /// 执行Action时发生错误请调用此方法
        /// </summary>
        /// <param name="Message"></param>
        /// <param name="code"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        protected void Error(string Message, int code = -1, object data = null)
        {
            //Log.Error("执行API发生错误:{0}\n{1}", "API", Message, code);
            SetHeader(this.Response);
            Response.AddHeader("Content-Type", "application/json");
            Response.Write((new ApiResult()
            {
                Success = false,
                Code = code,
                Message = Message,
                Data = data
            }).ToJson());
            Response.End();
        }

        /// <summary>
        /// 打印成功处理的json
        /// </summary>
        /// <param name="obj"></param>
        public void Success(object obj)
        {
            var response = this.Context.Response;
            SetHeader(response);
            response.AddHeader("Content-Type", "application/json");
            response.Write((new ApiResult()
            {
                Success = true,
                Data = obj
            }).ToJson());
            response.End();
        }

        /// <summary>
        /// API统一返回结构
        /// </summary>
        public class ApiResult
        {
            /// <summary>
            /// API是否执行成功
            /// </summary>
            public bool Success { get; set; }
            /// <summary>
            /// 错误代码
            /// </summary>
            public int Code { get; set; }
            /// <summary>
            /// 错误信息
            /// </summary>
            public string Message { get; set; }
            /// <summary>
            /// 扩展信息
            /// </summary>
            public string ExtMsg { get; set; }
            /// <summary>
            /// 返回数据
            /// </summary>
            public object Data { get; set; }
        }
    }
    #endregion
}
